// ajax model
import Vue from 'vue';
import axios from 'axios';
import { LoadingPlugin, querystring } from 'vux';

Vue.use(LoadingPlugin);

class BaseModel {
	constructor(props) {
		this.baseUrl = '/1.0.0/web/';
		this.url = 'apis/';
		this.settedUrl = this.url;
		this.showAjaxLoading = true; // 是否在request的时候进行loading
		this.method = 'post';
		this.timeout = 5000;
		this.hasSettedQuerys = false;
		this.data = {
			token: window.GLOBAL.TOKEN
		};
	}
	// 修改post传值参数
	setParams(params) {
		if (!this.hasSettedQuerys) {
			this.hasSettedQuerys = true;
			this.settedUrl = this.url;
		}
		this.data = Object.assign({}, this.data, params);
		return this;
	}
	// 修改get的queryString
	setQuerys(params) {
		let queryStr = querystring.stringify(params);
		this.hasSettedQuerys = true;
		this.setUrl(queryStr);
		return this;
	}
	setUrl(queryStr) {
		if (queryStr) {
			this.settedUrl = `${this.url}?${queryStr}`;
		} else {
			this.settedUrl = this.url;
		}
		return this;
	}
	go() {
		// this.setUrl();
		let url = `${this.baseUrl}${this.settedUrl}`;
		let { loading } = Vue.$vux;
		if (this.showAjaxLoading) {
			loading.show(' ');
		}
		let xhr = new Promise((resove, reject) => {
			axios({
				method: this.method,
				url,
				data: this.data,
				timeout: this.timeout
			})
			.then(rst => {
				// 正确请求中的code 200为正常值
				if (rst && rst.data && rst.data.code == 200) {
					resove(rst.data);
				} else {
					reject(rst.data);
				}
				loading.hide();
				this.setUrl();
			})
			.catch(err => {
				reject(err);
				loading.hide();
				this.setUrl();
			});
		});
		return xhr;
	}
}

export default BaseModel;